// Copyright (c) 2020 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/coinone/api_order/native_rest_async_asio_subscriber.h"

#include <glog/logging.h>

#include "coin2/base/time.h"
#include "coin2/exchange/coinone/api_order/native_private_client.h"
#include "coin2/exchange/order/coinone.pb.h"

namespace coin2::exchange::coinone::api_order {

void CoinoneRestAsyncAsioSubscriber::QueryBalance() {
  auto http_context = rest_client()->QueryAccountBalance();
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CoinoneRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CoinoneRestAsyncAsioSubscriber::QueryOpenOrders(const std::string& native_symbol) {
  RestParams params;
  params.set_currency(native_symbol);
  auto http_context = rest_client()->QueryLimitOrders(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CoinoneRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CoinoneRestAsyncAsioSubscriber::QueryFills(const std::string& native_symbol) {
  RestParams params;
  params.set_currency(native_symbol);
  auto http_context = rest_client()->QueryCompleteOrders(params);
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&CoinoneRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void CoinoneRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&CoinoneRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");

  auto symbol_list = native_symbols();

  AddPeriodicTask(
      std::bind(&CoinoneRestAsyncAsioSubscriber::QueryOpenOrders, this, std::placeholders::_1),
      config_.query_open_orders_period_sec(),
      "query_open_orders",
      symbol_list);

  AddPeriodicTask(
      std::bind(&CoinoneRestAsyncAsioSubscriber::QueryFills, this, std::placeholders::_1),
      config_.query_fill_period_sec(),
      "query_fills",
      symbol_list);
}

}  // namespace coin2::exchange::coinone::api_order
